<template>
  <span v-if="day === 0 && hour === 0 && minute === 0 && second === 0">
    <Link url="quiz" text="前往答题" />
  </span>
  <span v-else>
    {{ day === 0 ? "" : `${day} : ` }}
    {{ hour === 0 ? "00 : " : `${hour} : ` }}
    {{ minute === 0 ? "00 : " : `${minute} : ` }}
    {{ second === 0 ? "00" : second }}
  </span>
</template>

<script>
import { mapState } from "vuex";
import Link from "../Link.vue";

export default {
  data: () => ({
    FinalTimeout: 5 * 60 * 1000, // 5 分钟
    countTimeInMilliSeconds: undefined,
  }),
  components: { Link },
  computed: {
    day() {
      if (this.countTimeInMilliSeconds === undefined) return "00";
      const day = Math.floor(
        this.countTimeInMilliSeconds / 1000 / 60 / 60 / 24
      );
      return day < 10 && day > 0 ? `0${day}` : Math.max(day, 0);
    },
    hour() {
      if (this.countTimeInMilliSeconds === undefined) return "00";
      const hour =
        Math.floor(this.countTimeInMilliSeconds / 1000 / 60 / 60) % 24;
      return hour < 10 && hour > 0 ? `0${hour}` : Math.max(hour, 0);
    },
    minute() {
      if (this.countTimeInMilliSeconds === undefined) return "00";
      const minute = Math.floor(this.countTimeInMilliSeconds / 1000 / 60) % 60;
      return minute < 10 && minute > 0 ? `0${minute}` : Math.max(minute, 0);
    },
    second() {
      if (this.countTimeInMilliSeconds === undefined) return "00";
      const second = Math.floor(this.countTimeInMilliSeconds / 1000) % 60;
      return second < 10 && second > 0 ? `0${second}` : Math.max(second, 0);
    },
    ...mapState(["READING_TIME", "START_ANSWER_TIME"]),
  },
  methods: {
    timeReduce() {
      this.countTimeInMilliSeconds =
        this.START_ANSWER_TIME === ""
          ? 0
          : +new Date(this.START_ANSWER_TIME) - +Date.now();
      if (this.countTimeInMilliSeconds > 0) {
        setTimeout(this.timeReduce, 1000);
        this.finalTimeout();
      } else {
        this.$emit("timeout");
      }
    },
    finalTimeout() {
      if (this.countTimeInMilliSeconds <= this.FinalTimeout) {
        this.$emit("finalTimeout");
        this.finalTimeout = () => {};
      }
    },
  },
  mounted() {
    this.timeReduce();
  },
};
</script>

<style></style>
